﻿using System;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using Prism.Logging;

namespace System
{
    public class Log4NetLogger
    {
        #region 成员
        /// <summary>
        /// 错误日志对象
        /// </summary>
        private ILog _errorLogger;

        /// <summary>
        /// 普通日志对象
        /// </summary>
        private ILog _infoLogger;
        #endregion

        #region 构造
        public Log4NetLogger()
        {
            var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
            XmlConfigurator.Configure(logRepository, new FileInfo("log.config"));

            _errorLogger = LogManager.GetLogger(logRepository.Name, "logerror");
            _infoLogger = LogManager.GetLogger(logRepository.Name, "loginfo");
            Log("日志初始化", Category.Info);
        }
        #endregion

        #region 方法
        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="message"></param>
        /// <param name="category"></param>
        /// <param name="priority"></param>
        private void Log(string message, Category category, Priority priority = Priority.None)
        {
            switch (category)
            {
                case Category.Debug:
                case Category.Info:
                case Category.Warn:
                    _infoLogger.Error(message ?? "");
                    break;
                case Category.Exception:
                    _errorLogger.Error(message ?? "");
                    break;
            }
        }

        /// <summary>
        /// 异常日志
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="msg"></param>
        public void Log(Exception ex, string msg = "")
        {
            if (msg == null)
                msg = string.Empty;
            Log(msg + ex.ToString(), Category.Exception, Priority.High);
        }

        /// <summary>
        /// Info日志
        /// </summary>
        /// <param name="msg"></param>
        public void Log(string msg)
        {
            Log(msg, Category.Info, Priority.None);
        } 
        #endregion
    }
}
